<?php

namespace app\common\logic\video;

use app\common\logic\BaseLogic;
use Grpc\ChannelCredentials;
use Pb\M3u8Request;
use Pb\VideoClient;

class VideoLogic extends BaseLogic
{
    public function rpcM3u8ByChapterId(int $chapterId): false|string
    {
        try {
            $videoClient = new VideoClient(grpc_address(), [
                'credentials' => ChannelCredentials::createInsecure()
            ]);

            $request = new M3u8Request();

            $request->setChapterId($chapterId);

            $request = $videoClient->M3u8Url($request)->wait();

            /** @var \Pb\M3u8Response $response */
            list($response, $state) = $request;
            if ($state->code != 0) {
                throw new \Exception(sprintf('[%d]%s', $state->code, $state->details));
            }
            if (is_null($response)) {
                throw new \Exception("系统错误");
            }

            return $response->getUrl();

        } catch (\Throwable $exception) {
            return $this->setMessage($exception->getMessage());
        }
    }
}